package com.pavco.caribbeanvisit.client;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.pavco.caribbeanvisit.client.presenter.MainPresenter;
import com.pavco.caribbeanvisit.client.presenter.Presenter;
import com.pavco.caribbeanvisit.client.view.MainView;

public class AppController implements ValueChangeHandler<String> {
  private final HandlerManager eventBus;
  private HasWidgets container;
  private final RpcServiceAsync rpcService;
  
  public AppController(RpcServiceAsync rpcService,
      HandlerManager eventBus) {
    this.eventBus = eventBus;
    this.rpcService = rpcService;
    bind();
  }

  private void bind() {
    History.addValueChangeHandler(this);
  }
  
  @Override
  public void onValueChange(ValueChangeEvent<String> event) {
    String token = event.getValue();
    
    if (token != null) {
      Presenter presenter = null;
      
      if (token.equals("beginning")) {
        presenter = new MainPresenter(rpcService, eventBus, new MainView());
      }
      
      if (presenter != null) {
        presenter.go(container);
      }
    }
  }
  
  public void go(final HasWidgets container) {
    this.container = container;
    
    if ("".equals(History.getToken())) {
      History.newItem("beginning");
    } else {
      History.fireCurrentHistoryState();
    }
  }
}